package com.tnl.hunter.webchat.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.biz.qq.wechat.api.AuthenticationAPI;
import com.biz.qq.wechat.entity.AuthToken;
import com.biz.system.config.SystemConfig;
import com.biz.system.config.WebchatServiceConstant;

/** * OAuth2 处理控制器 */
@Controller
public class OAuth2Controller {
	
	private static final String domainName = SystemConfig.getProperties("Domain");

	private Logger logger = LoggerFactory
			.getLogger(OAuth2Controller.class);

	/**
	 * * 构造参数并将请求重定向到微信API获取登录信息 *
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "wechat/oauth2.do")
	public String Oauth2API(HttpServletRequest request,
			@RequestParam String resultUrl) {

		String redirectUrl = "";
		if (resultUrl == null) {
			return "";
		}
//		String reqUrl = request.getLocalAddr();
		request.getRequestURI();
		logger.debug("remoted addr is "+request.getRemoteAddr());
		logger.debug("local addr is "+request.getLocalAddr());
		String contextPath = request.getContextPath();
		logger.debug("contextPath is "+contextPath);
		String domain = SystemConfig.getProperties("Domain");
		
		String backUrl = "https://"+domain+"/tnl-hunter/wechat/oauth2url.do?oauth2url="
				+ resultUrl;
		logger.debug("backUrl=" + backUrl);
		redirectUrl = AuthenticationAPI.getAuthorizeUrl(backUrl,WebchatServiceConstant.APPID);

		return "redirect:" + redirectUrl;
	}

	@RequestMapping(value = { "wechat/oauth2url.do" })
	public String Oauth2MeUrl(HttpServletRequest request,
			 @RequestParam String oauth2url) {
		String code = request.getParameter("code"); 
		if (!StringUtils.hasText(code)) {
			logger.error("the return code is empty/null");
			return "error";
		}
		String openID = getOpenidFromToken(code);
		if (StringUtils.isEmpty(openID)) {
			
			return "error";//出错了，请稍后再试
		}
		logger.debug("code is " +code);
		logger.debug("OpenId set session attribute " +openID);
		HttpSession session = request.getSession();
		session.setAttribute("OpenId", openID);
		return "redirect:" + oauth2url;
	}

	private String getOpenidFromToken(String code) {
		logger.info("use code to call getAuthToken.");
		AuthToken authToken = AuthenticationAPI.getAuthToken(code,
				WebchatServiceConstant.APPID,WebchatServiceConstant.APPSECRET);

		String openid = null;
		if (authToken == null) {
			logger.error("can not get the accesstoken which contains the openid");
			return null;
		}
		openid = authToken.getOpenid();
		logger.info("token from weixin:" + openid);
		return openid;
	}

}
